/**
 * 字体加载检测工具
 * @description 检测字体加载状态，提供字体加载优化
 * @author 零の守墓人
 * @version 1.0.0
 */

interface FontFace {
    family: string;
    weight?: string;
    style?: string;
}

/**
 * 字体加载检测器类
 */
class FontLoader {
    private fonts: FontFace[] = [
        { family: 'PingFang SC' },
        { family: 'Microsoft YaHei' },
        { family: 'Inter' },
        { family: 'Roboto' }
    ];

    private loadedFonts: Set<string> = new Set();

    /**
     * 初始化字体加载检测
     */
    init(): void {
        this.detectFonts();
        this.addFontLoadingClasses();
    }

    /**
     * 检测字体是否已加载
     * @param fontFamily 字体族名称
     * @returns 字体是否已加载
     */
    private isFontLoaded(fontFamily: string): boolean {
        const testString = 'abcdefghijklmnopqrstuvwxyz0123456789';
        const testSize = '72px';
        const canvas = document.createElement('canvas');
        const context = canvas.getContext('2d');

        if (!context) return false;

        // 测试默认字体
        context.font = `${testSize} sans-serif`;
        const defaultWidth = context.measureText(testString).width;

        // 测试目标字体
        context.font = `${testSize} "${fontFamily}", sans-serif`;
        const targetWidth = context.measureText(testString).width;

        return defaultWidth !== targetWidth;
    }

    /**
     * 检测所有字体
     */
    private detectFonts(): void {
        this.fonts.forEach(font => {
            if (this.isFontLoaded(font.family)) {
                this.loadedFonts.add(font.family);
            }
        });
    }

    /**
     * 添加字体加载类
     */
    private addFontLoadingClasses(): void {
        const body = document.body;

        // 添加字体加载状态类
        body.classList.add('font-loading');

        // 检测字体加载完成
        const checkFontsLoaded = () => {
            this.detectFonts();

            if (this.loadedFonts.size >= this.fonts.length) {
                body.classList.remove('font-loading');
                body.classList.add('font-loaded');
                console.log('所有字体加载完成');
            } else {
                // 继续检测
                setTimeout(checkFontsLoaded, 100);
            }
        };

        // 开始检测
        setTimeout(checkFontsLoaded, 100);
    }

    /**
     * 获取字体加载状态
     * @returns 字体加载状态信息
     */
    getFontStatus(): { loaded: string[]; total: number } {
        return {
            loaded: Array.from(this.loadedFonts),
            total: this.fonts.length
        };
    }

    /**
     * 预加载字体
     * @param fontFamily 字体族名称
     */
    preloadFont(fontFamily: string): void {
        const link = document.createElement('link');
        link.rel = 'preload';
        link.as = 'font';
        link.href = `https://fonts.googleapis.com/css2?family=${fontFamily}:wght@300;400;500;600;700&display=swap`;
        document.head.appendChild(link);
    }

    /**
     * 优化字体显示
     */
    optimizeFontDisplay(): void {
        // 添加字体显示优化
        const style = document.createElement('style');
        style.textContent = `
            * {
                font-display: swap;
            }
            
            .font-optimized {
                -webkit-font-smoothing: antialiased;
                -moz-osx-font-smoothing: grayscale;
                text-rendering: optimizeLegibility;
            }
        `;
        document.head.appendChild(style);
    }
}

// 创建全局字体加载器实例
export const fontLoader = new FontLoader();

/**
 * 字体加载优化工具函数
 */
export const fontUtils = {
    /**
     * 初始化字体优化
     */
    init(): void {
        fontLoader.init();
        fontLoader.optimizeFontDisplay();
    },

    /**
     * 获取字体状态
     */
    getStatus() {
        return fontLoader.getFontStatus();
    },

    /**
     * 预加载指定字体
     */
    preload(fontFamily: string): void {
        fontLoader.preloadFont(fontFamily);
    },

    /**
     * 添加字体优化类
     */
    addOptimizationClass(element: HTMLElement): void {
        element.classList.add('font-optimized');
    },

    /**
     * 移除字体优化类
     */
    removeOptimizationClass(element: HTMLElement): void {
        element.classList.remove('font-optimized');
    }
};

// 自动初始化字体加载器
if (typeof window !== 'undefined') {
    fontUtils.init();
} 